package leetcode;

import java.util.*;
import java.util.stream.Collectors;

public class Lc1336_2 {



    public String rankTeams(String[] votes) {

        HashMap<Character, int[]> map = new HashMap<>();
        Character[] chars = new Character[votes[0].length()];
        for (int i = 0; i < votes[0].length(); i++) {
            chars[i] = votes[0].charAt(i);
        }
        for (int i = 0; i < votes.length; i++) {
            String str = votes[i];
            for (int j = 0; j < str.length(); j++) {
                int[] rank = map.getOrDefault(str.charAt(j), new int[votes[0].length()]);
                rank[j]++;
                map.put(str.charAt(j), rank);
            }
        }

        Arrays.sort(chars, new Comparator<Character>() {
            @Override
            public int compare(Character o1, Character o2) {
                int[] rank1 = map.get(o1);
                int[] rank2 = map.get(o2);
                for (int i = 0; i < rank1.length; i++) {
                    if (rank1[i] != rank2[i])
                        return rank1[i] - rank2[i];
                }
                return o1.compareTo(o2);
            }
        });
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            builder.append(chars[i]);
        }
        return builder.reverse().toString();
    }


}
